package com.aos;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.StringBufferInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;

public class Server extends Thread
{
	public static int connectionCount;
	public static Semaphore accessSemaphore = new Semaphore(100, true);
	
	public void run()
	{
		try {
			ServerSocket server = new ServerSocket(Node.nodeInfo.getPort());
			Socket listenerSocket = new Socket();
			BufferedReader listenerStreamReader;
			
			while(getConnectionCounter() != Node.neighbors.size()) //check whether a socket has been established with all neighbors
			{
				listenerSocket = server.accept();
				listenerStreamReader = new BufferedReader(new InputStreamReader(listenerSocket.getInputStream()));
				
				Listener listener = new Listener(listenerSocket, listenerStreamReader);
				new Thread(listener).start();
				
				incConnectionCounter();
			}
			
			server.close();
		} catch (IOException e) {			
			e.printStackTrace();
		}
		//System.out.println("Server started...");
		Node.updateNodeState();		
	}
	
	public static synchronized int getConnectionCounter()
	{
		int count = -1;
		try {
			accessSemaphore.acquire();
			count = connectionCount;
			accessSemaphore.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public static synchronized void incConnectionCounter()
	{
		try
		{
			accessSemaphore.acquire();
			connectionCount++;
			accessSemaphore.release();
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		
	}
}
